#include "mainwindow.h"
#include "dialog/loggingindialog.h"
#include "globalsignal.h"
#include "qevent.h"
#include "ui_mainwindow.h"
#include "dialog/logindialog.h"
#include"maininterface.h"
#include"httpmgr.h"
#include "usermgr.h"
#include"save.h"
#include <QFile>
#include <QScreen>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // setWindowFlags(Qt::FramelessWindowHint);
    initHandlers();
    connect(HttpMgr::GetInstance().get(), &HttpMgr::sig_global_mod_finish, this, &MainWindow::slot_global_mod_finish);

    // QJsonObject json_obj;
    // json_obj["machineCode"] = MachineCode;
    // HttpMgr::GetInstance()->PostHttpReq(QUrl(GATE_URL+"/user/checkUser"),
    //                                     QJsonDocument(json_obj).toJson(), ReqId::ID_CHECK_USER,Modules::GLOBALMOD);
    initFile();

    switchLogInDialog();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initHandlers()
{
    _handlers.insert(std::make_pair(ReqId::ID_CHECK_USER, [this](QJsonObject jsonObj){
        int error = jsonObj["error"].toInt();
        qDebug() << error;
        if(static_cast<ErrorCodes>(error) != ErrorCodes::SUCCESS){
            switchLogInDialog();
            return;
        }
        QString name{jsonObj["user"].toString()};
        ui->label_2->setText(name);

        isGetAvatar(name);
        ui->label->setPixmap(QPixmap(AvatarPath.arg(name)));
    }));
    _handlers.insert(std::make_pair(ReqId::ID_AUTO_LOGIN_USER, [this](QJsonObject jsonObj){
        int error = jsonObj["error"].toInt();
        if(static_cast<ErrorCodes>(error) != ErrorCodes::SUCCESS){
            switchLogInDialog();
            return;
        }

        int _uid = jsonObj["uid"].toInt();
        QString _token = jsonObj["token"].toString();

        _user =  jsonObj["user"].toString();
        ServerInfo si;
        si.user = jsonObj["user"].toString();
        si.Uid = _uid;
        si.Host = jsonObj["host"].toString();
        si.Port = jsonObj["port"].toString();
        si.Token = _token;

        qDebug()<< "user is " << si.user << "通过网关服务器";
        slot_logIn_tcp(si);
    }));
    _handlers.insert(std::make_pair(ReqId::ID_Get_AVATAR, [this](QJsonObject jsonObj){
        int error = jsonObj["error"].toInt();
        if(static_cast<ErrorCodes>(error) != ErrorCodes::SUCCESS){
            return;
        }
        QString filePath{FileAvatar + jsonObj["user"].toString() + "_Avatar.jpg"};

        // 将Base64编码的字符串解码为QByteArray
        QByteArray base64Data = QByteArray::fromBase64(jsonObj["avatar"].toString().toLocal8Bit());
        // 将QByteArray保存为文件
        QFile outputFile(filePath);
        if (!outputFile.open(QIODevice::WriteOnly)) {
            qDebug() << "无法打开文件进行写入";
            return ;
        }

        // 写入解码后的数据到文件
        outputFile.write(base64Data);
        outputFile.close();

        if (_isCentre)
            ui->label->setPixmap(QPixmap(filePath));
    }));
    _handlers.insert(std::make_pair(ReqId::ID_GET_FRIEND_LIST, [](QJsonObject jsonObj){
        int error = jsonObj["error"].toInt();
        if(static_cast<ErrorCodes>(error) != ErrorCodes::SUCCESS){
            return;
        }
        // 处理 friends
        QJsonArray friendsArray = jsonObj["friends"].toArray();
        for (const QJsonValue &value : friendsArray){
            QJsonObject friendObject = value.toObject();
            QString name = friendObject["user"].toString();
            isGetAvatar(name);
            emit GlobalSignal::GetInstance()->sig_add_friend(name);
        }

        // 处理 pending_requests
        QJsonArray pendingRequestsArray = jsonObj["pending_requests"].toArray();
        for (const QJsonValue &value : pendingRequestsArray){
            QJsonObject requestObject = value.toObject();
            QString name = requestObject["user"].toString();
             isGetAvatar(name);
             emit GlobalSignal::GetInstance()->sig_add_friend_req(name, requestObject["message"].toString());
        }
    }));
    _handlers.insert(std::make_pair(ReqId::ID_GET_OFFLINE_MSG, [](QJsonObject jsonObj){
        int error = jsonObj["error"].toInt();
        if(static_cast<ErrorCodes>(error) != ErrorCodes::SUCCESS){
            return;
        }
        qDebug("离线消息");

        QJsonArray Array = jsonObj["offline_message"].toArray();
        for (const QJsonValue &value : Array){
            QJsonObject friendObject = value.toObject();
            QString sender = friendObject["sender"].toString();
            QString message = friendObject["message"].toString();
            QString timestamp = friendObject["timestamp"].toString();
            QDateTime dateTime = QDateTime::fromString(timestamp, Qt::ISODate);
            qDebug() << "历史消息的时间" << dateTime;
            Save::GetInstance()->Add(friendObject["message_id"].toInt(), sender, message, friendObject["message_type"].toString(), sender, dateTime);
            emit GlobalSignal::GetInstance()->sig_add_offline_text_msg(sender, message, dateTime);
        }
    }));
}


void MainWindow::switchLogInDialog()
{
    _isCentre = false;
    LogInDialog *logIn = new LogInDialog(this);
    logIn->setWindowFlags(Qt::CustomizeWindowHint|Qt::FramelessWindowHint);
    setCentralWidget(logIn);
    logIn->show();
    resize(380, 440);

    alignCenter();

    connect(logIn, &LogInDialog::sig_logIn_tcp, this, &MainWindow::slot_logIn_tcp);
}

void MainWindow::initFile()
{
    QDir dir;
    if (!QDir(FileData).exists()){
        dir.mkpath(FileData);
    }
    if (!QDir(FileOtherFiles).exists()){
        dir.mkpath(FileOtherFiles);
    }
    if (!QDir(FileChattingRecords).exists()){
        dir.mkpath(FileChattingRecords);
    }
    if (!QDir(FileAvatar).exists()){
        dir.mkpath(FileAvatar);
    }
}

void MainWindow::slot_logIn_tcp(const ServerInfo& s)
{
    _isCentre = false;
    LoggingInDialog *l = new LoggingInDialog(this);
    l->setPixmap(QPixmap{FileAvatar + s.user + "_Avatar.jpg"});
    connect(l, &LoggingInDialog::sig_switch_main, this, &MainWindow::slot_switch_main);
    l->setWindowFlags(Qt::CustomizeWindowHint|Qt::FramelessWindowHint);
    resize(299, 327);

    alignCenter();

    this->setCentralWidget(l);
    l->show();
    l->connectTcp(s);
}

void MainWindow::alignCenter()
{
    QScreen *screen = QGuiApplication::primaryScreen();
    QRect screenGeometry = screen->availableGeometry();
    QSize windowSize = this->size();
    QPoint centerPoint(screenGeometry.center().x() - windowSize.width() / 2,
                       screenGeometry.center().y() - windowSize.height() / 2);
    this->move(centerPoint);
}

void MainWindow::slot_switch_main(const QString& user)
{
    _isCentre = false;
    MainInterface *c = new MainInterface(this);
    c->setPixmap(QPixmap{FileAvatar + user + "_Avatar.jpg"});
    connect(c, &MainInterface::sig_exit_chat, this, &MainWindow::switchLogInDialog);
    resize(1100, 700);
    c->setWindowFlags(Qt::CustomizeWindowHint|Qt::FramelessWindowHint);

    alignCenter();

    this->setCentralWidget(c);
    c->show();
    qDebug() << "登录了";

    QJsonObject json_obj;
    json_obj["user_id"] = UserMgr::GetInstance()->getUid();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(GATE_URL+"/user/friendList"),
                                        QJsonDocument(json_obj).toJson(), ReqId::ID_GET_FRIEND_LIST,Modules::GLOBALMOD);
}

void MainWindow::on_switchBtn_clicked()
{
    switchLogInDialog();
}

void MainWindow::slot_global_mod_finish(QByteArray data, ReqId id, ErrorCodes err)
{
    QJsonParseError jsonError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);

    if (jsonError.error != QJsonParseError::NoError){
        qDebug() << "JSON解析错误：" << jsonError.errorString();
    }
    _handlers[id](jsonDoc.object());
}

void MainWindow::on_logInBtn_clicked()
{
    QJsonObject json_obj;
    json_obj["machineCode"] = MachineCode;
    json_obj["user"] = ui->label_2->text();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(GATE_URL+"/user/autoLogin"),
                                        QJsonDocument(json_obj).toJson(), ReqId::ID_AUTO_LOGIN_USER,Modules::GLOBALMOD);
}
